import { defineStore } from 'pinia'
import { useAppStore } from './app'
import { v4 as uuidv4 } from 'uuid'

export const useTabStore = defineStore('tab', {
  state: () => ({
    // 标签页列表
    tabs: [],
    
    // 当前激活的标签页ID
    activeTabId: null,
    
    // 标签页计数器（用于生成唯一ID）
    tabCounter: 0
  }),
  
  getters: {
    // 获取激活的标签页
    activeTab: (state) => {
      return state.tabs.find(tab => tab.id === state.activeTabId)
    },
    
    // 获取指定连接的标签页
    getTabsByConnection: (state) => (connectionId) => {
      return state.tabs.filter(tab => tab.connectionId === connectionId)
    },
    
    // 获取指定类型的标签页
    getTabsByType: (state) => (type) => {
      return state.tabs.filter(tab => tab.type === type)
    },
    
    // 检查是否有未保存的标签页
    hasUnsavedTabs: (state) => {
      return state.tabs.some(tab => tab.unsaved)
    },
    
    // 获取未保存的标签页列表
    unsavedTabs: (state) => {
      return state.tabs.filter(tab => tab.unsaved)
    }
  },
  
  actions: {
    // 创建新标签页
    createTab(options) {
      const appStore = useAppStore()
      
      // 检查最大标签页数量限制
      if (this.tabs.length >= appStore.settings.maxTabs) {
        ElMessage.warning(`最多只能打开${appStore.settings.maxTabs}个标签页`)
        return null
      }
      
      const tab = {
        id: `tab_${++this.tabCounter}`,
        type: options.type || 'query',
        title: options.title || '新建查询',
        icon: options.icon || 'Document',
        connectionId: options.connectionId,
        database: options.database,
        table: options.table,
        closable: options.closable !== false,
        unsaved: false,
        data: options.data || {},
        meta: options.meta || {},
        createdAt: new Date(),
        lastActiveAt: new Date()
      }
      
      // 检查是否已存在相同的标签页
      const existingTab = this.findSimilarTab(tab)
      if (existingTab) {
        this.setActiveTab(existingTab.id)
        return existingTab
      }
      
      this.tabs.push(tab)
      this.setActiveTab(tab.id)
      
      return tab
    },
    
    // 查找相似的标签页
    findSimilarTab(newTab) {
      // Allow multiple tabs of all types by default
      return null;
      
      // Original behavior for reference (commented out):
      /*
      return this.tabs.find(tab => {
        if (tab.type !== newTab.type) return false
        if (tab.connectionId !== newTab.connectionId) return false
        
        switch (newTab.type) {
          case 'query':
            return false // 查询标签页允许多个
          case 'browse':
            return tab.database === newTab.database && tab.table === newTab.table
          case 'design':
            return tab.database === newTab.database && tab.table === newTab.table
          default:
            return false
        }
      })
      */
    },
    
    // 创建查询标签页
    createQueryTab(connectionId, options = {}) {
      return this.createTab({
        type: 'query',
        title: options.title || '新建查询',
        icon: 'Document',
        connectionId,
        database: options.database || null, // 确保数据库名称被传递
        data: {
          sql: options.sql || '',
          results: null,
          history: []
        },
        ...options
      })
    },
    
    // 创建数据浏览标签页
    createBrowseTab(connectionId, database, table, options = {}) {
      return this.createTab({
        type: 'browse',
        title: options.title || `${table} - 数据`,
        icon: 'View',
        connectionId,
        database,
        table,
        data: {
          filters: {},
          sorting: {},
          pagination: { page: 1, size: 100 }
        },
        ...options
      })
    },
    
    // 创建表设计标签页
    createDesignTab(connectionId, database, table = null, options = {}) {
      const isNewTable = !table
      return this.createTab({
        type: 'design',
        title: options.title || (isNewTable ? '新建表' : `${table} - 设计`),
        icon: 'Edit',
        connectionId,
        database,
        table,
        data: {
          columns: [],
          indexes: [],
          foreignKeys: [],
          isNewTable
        },
        ...options
      })
    },
    
    // 创建表浏览标签页 (原本是重复的createBrowseTab)
    createSingleTableBrowserTab(connectionId, database, table) {
      this.createTab({
        id: uuidv4(),
        title: `${table} (${database})`,
        type: 'browse',
        connectionId,
        data: {
          database,
          table
        }
      })
    },
    
    // 创建多表浏览标签页
    createTableBrowserTab(connectionId, database, options = {}) {
      this.createTab({
        id: uuidv4(),
        title: options.title || `表浏览 (${database})`,
        type: 'tablesBrowser',
        connectionId,
        data: {
          database,
          tables: options.tables || []
        }
      })
    },
    
    // 设置激活标签页
    setActiveTab(tabId) {
      const tab = this.tabs.find(t => t.id === tabId)
      if (tab) {
        this.activeTabId = tabId
        tab.lastActiveAt = new Date()
      }
    },
    
    // 关闭标签页
    async closeTab(tabId, force = false) {
      const tab = this.tabs.find(t => t.id === tabId)
      if (!tab) return
      
      // 检查是否有未保存的更改
      if (!force && tab.unsaved) {
        const result = await this.confirmCloseUnsavedTab(tab)
        if (!result) return false
      }
      
      const index = this.tabs.findIndex(t => t.id === tabId)
      if (index === -1) return false
      
      // 移除标签页
      this.tabs.splice(index, 1)
      
      // 如果关闭的是当前激活的标签页，需要激活其他标签页
      if (this.activeTabId === tabId) {
        if (this.tabs.length > 0) {
          // 激活相邻的标签页
          const newIndex = Math.min(index, this.tabs.length - 1)
          this.setActiveTab(this.tabs[newIndex].id)
        } else {
          this.activeTabId = null
        }
      }
      
      return true
    },
    
    // 关闭其他标签页
    async closeOtherTabs(keepTabId) {
      const tabsToClose = this.tabs.filter(tab => tab.id !== keepTabId)
      
      for (const tab of tabsToClose) {
        const closed = await this.closeTab(tab.id)
        if (!closed) break // 用户取消了关闭操作
      }
    },
    
    // 关闭所有标签页
    async closeAllTabs() {
      const unsavedTabs = this.unsavedTabs
      if (unsavedTabs.length > 0) {
        const result = await this.confirmCloseAllUnsavedTabs(unsavedTabs)
        if (!result) return false
      }
      
      this.tabs = []
      this.activeTabId = null
      return true
    },
    
    // 关闭指定连接的所有标签页
    async closeConnectionTabs(connectionId) {
      const connectionTabs = this.getTabsByConnection(connectionId)
      
      for (const tab of connectionTabs) {
        await this.closeTab(tab.id)
      }
    },
    
    // 更新标签页
    updateTab(tabId, updates) {
      const tab = this.tabs.find(t => t.id === tabId)
      if (tab) {
        Object.assign(tab, updates)
        
        // 如果更新了数据，标记为未保存
        if (updates.data && !updates.hasOwnProperty('unsaved')) {
          tab.unsaved = true
        }
      }
    },
    
    // 更新标签页数据
    updateTabData(tabId, data) {
      const tab = this.tabs.find(t => t.id === tabId)
      if (tab) {
        tab.data = { ...tab.data, ...data }
        tab.unsaved = true
      }
    },
    
    // 标记标签页为已保存
    markTabSaved(tabId) {
      const tab = this.tabs.find(t => t.id === tabId)
      if (tab) {
        tab.unsaved = false
      }
    },
    
    // 重命名标签页
    renameTab(tabId, newTitle) {
      const tab = this.tabs.find(t => t.id === tabId)
      if (tab) {
        tab.title = newTitle
      }
    },
    
    // 复制标签页
    duplicateTab(tabId) {
      const tab = this.tabs.find(t => t.id === tabId)
      if (!tab) return null
      
      return this.createTab({
        type: tab.type,
        title: `${tab.title} - 副本`,
        icon: tab.icon,
        connectionId: tab.connectionId,
        database: tab.database,
        table: tab.table,
        data: cloneDeep(tab.data),
        meta: cloneDeep(tab.meta)
      })
    },
    
    // 移动标签页
    moveTab(fromIndex, toIndex) {
      if (fromIndex === toIndex) return
      
      const tab = this.tabs.splice(fromIndex, 1)[0]
      this.tabs.splice(toIndex, 0, tab)
    },
    
    // 确认关闭未保存的标签页
    async confirmCloseUnsavedTab(tab) {
      return new Promise((resolve) => {
        ElMessageBox.confirm(
          `标签页 "${tab.title}" 有未保存的更改，确定要关闭吗？`,
          '确认关闭',
          {
            confirmButtonText: '关闭',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          resolve(true)
        }).catch(() => {
          resolve(false)
        })
      })
    },
    
    // 确认关闭所有未保存的标签页
    async confirmCloseAllUnsavedTabs(unsavedTabs) {
      return new Promise((resolve) => {
        const tabNames = unsavedTabs.map(tab => tab.title).join('、')
        ElMessageBox.confirm(
          `以下标签页有未保存的更改：${tabNames}，确定要全部关闭吗？`,
          '确认关闭',
          {
            confirmButtonText: '全部关闭',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          resolve(true)
        }).catch(() => {
          resolve(false)
        })
      })
    },
    
    // 获取标签页历史记录
    getTabHistory() {
      return this.tabs
        .slice()
        .sort((a, b) => new Date(b.lastActiveAt) - new Date(a.lastActiveAt))
        .slice(0, 10)
    },
    
    // 恢复标签页会话
    restoreSession(sessionData) {
      if (sessionData && sessionData.tabs) {
        this.tabs = sessionData.tabs
        this.activeTabId = sessionData.activeTabId
        this.tabCounter = sessionData.tabCounter || this.tabs.length
      }
    },
    
    // 保存标签页会话
    saveSession() {
      return {
        tabs: this.tabs,
        activeTabId: this.activeTabId,
        tabCounter: this.tabCounter
      }
    },
    
    // 重置store
    reset() {
      this.tabs = []
      this.activeTabId = null
      this.tabCounter = 0
    }
  }
}) 